<template>
    <div>
        <div v-if="searchResults.length" class="search-results-container">
            <div v-for="item in searchResults" :key="item.id">
                <SearchItem :searchData="item" />
            </div>
        </div>
        <div v-else>
            <p>没有找到结果</p>
        </div>
    </div>
</template>
  
<script>
import axios from 'axios';
import SearchItem from './SearchItem.vue';

export default {
    name: "SearchResults",
    // props: ['searchQuery'],
    data() {
        return {
            searchResults: [],
        };
    },
    components: {
        SearchItem,
    },
    watch: {
        searchQuery(newVal) {
            this.fetchCoffees(newVal);
        }
    },
    created() {
        this.fetchCoffees(this.$route.params.searchQuery);
    },
    methods: {
        fetchCoffees(query) {
            if (!query) {
                this.$router.push({ path: '/' });
                return;
            }
            axios.get('/coffees/coffees')
                .then(response => {
                    console.log(response)
                    console.log(query)
                    const allCoffees = Array.isArray(response.data) ? response.data : [];
                    let filteredCoffees = [];

                    allCoffees.forEach(info => {
                        info.details.forEach(coffee => {
                            if (coffee && coffee.chineseName) {
                                // 使用includes方法进行模糊匹配
                                if (coffee.chineseName.toLowerCase().includes(query.toLowerCase())) {
                                    filteredCoffees.push(coffee);
                                }
                            } else {
                                console.warn('Missing chineseName property in coffee object:', coffee);
                            }
                        });
                    });

                    this.searchResults = filteredCoffees;
                    console.log(this.searchResults);
                })
                .catch(error => {
                    console.error("获取搜索结果时出错:", error);
                });
        }
    }
};
</script>

<style scoped>
.search-results-container {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
}
</style>